package com.rc.saas.tenant.service.shop;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.member.MemberAccountMapper;
import com.rc.saas.tenant.mapper.member.MemberInfoMapper;
import com.rc.saas.tenant.mapper.shop.ShopGoodsMapper;
import com.rc.saas.tenant.mapper.shop.ShopOrderMapper;
import com.rc.saas.tenant.mapper.shop.ShopOrderReturnApplyMapper;
import com.rc.saas.tenant.mapper.shop.ShopStockRecordMapper;
import com.rc.saas.tenant.mapper.ticket.MemberTicketMapper;
import com.rc.saas.tenant.mapper.ticket.TenantTicketSendRecordMapper;
import com.rc.saas.tenant.mapper.ugs.UgsMemberPointRecordMapper;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.shop.*;
import com.rc.saas.tenant.model.ticket.MemberTicket;
import com.rc.saas.tenant.model.ticket.MemberTicketExample;
import com.rc.saas.tenant.model.ticket.TenantTicketSendRecordExample;
import com.rc.saas.tenant.model.ticket.TenantTicketType;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.model.ugs.UgsMemberPointRecord;
import com.rc.saas.tenant.model.ugs.UgsMemberPointRecordExample;
import com.rc.saas.tenant.search.shop.ShopGoodSearch;
import com.rc.saas.tenant.search.shop.ShopStockRecordSearch;
import com.rc.saas.tenant.service.shop.ShopGoodsService;
import com.rc.saas.tenant.service.ticket.TenantTicketTypeService;
import com.rc.saas.tenant.upyun.WebUploader;
import com.rc.saas.tenant.vo.shop.ShopGoodsVo;
import com.rc.saas.tenant.vo.shop.ShopOrderResultVo;
import com.upyun.UpException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class ShopGoodsServiceImpl implements ShopGoodsService {
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    @Autowired
    private ShopGoodsImageService shopGoodsImageService;

    @Autowired
    private ShopStockRecordService shopStockRecordService;

    @Autowired
    private ShopOrderGoodsService shopOrderGoodsService;

    @Autowired
    private TenantTicketTypeService tenantTicketTypeService;

    @Autowired
    private ShopGoodsClassService shopGoodsClassService;

    @Autowired
    private ShopStockRecordMapper shopStockRecordMapper;

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private UgsMemberPointRecordMapper ugsMemberPointRecordMapper;

    @Autowired
    private MemberAccountMapper memberAccountMapper;

    @Autowired
    private MemberTicketMapper memberTicketMapper;

    @Autowired
    private TenantTicketSendRecordMapper tenantTicketSendRecordMapper;

    @Autowired
    private ShopOrderReturnApplyMapper shopOrderReturnApplyMapper;

    @Override
    public ShopGoodsMapper getMapper() {
        return shopGoodsMapper;
    }

    @Override
    public PageInfo<ShopGoodsVo> listPageByCondition(ShopGoodSearch shopGoodSearch) {
        PageHelper.startPage(shopGoodSearch.getOffset(), shopGoodSearch.getLimit());
        List<ShopGoodsVo> shopOrderResultVos = shopGoodsMapper.listByCondition(shopGoodSearch);
        return new PageInfo<>(shopOrderResultVos);
    }

    @Override
    public TResponse saveOrUpdateShopOrder(ShopGoodsVo shopGoodsVo) {
        try {

            //class_type数据查找
            List<ShopGoodsClass> shopGoodsClassList = shopGoodsClassService.listByTenantCode(shopGoodsVo.getTenantCode());
            if (shopGoodsClassList.size() == 0) {
                //数据初始化
                shopGoodsClassService.initData(shopGoodsVo.getTenantCode());
                //重新查询
                shopGoodsClassList = shopGoodsClassService.listByTenantCode(shopGoodsVo.getTenantCode());
            }
            if (shopGoodsVo.getClassType() != null) {
                ShopGoodsClass shopGoodsClass1 =
                        shopGoodsClassList.stream().filter(shopGoodsClass -> shopGoodsVo.getClassType().equals(shopGoodsClass.getClassType())).findFirst().orElseGet(() -> null);
                shopGoodsVo.setGoodsClassId(shopGoodsClass1.getGoodsClassId());

            }
            ShopGoods shopGoods = new ShopGoods();
            BeanUtils.copyProperties(shopGoodsVo, shopGoods);

            ShopGoodsImage shopGoodsImage = new ShopGoodsImage();
            BeanUtils.copyProperties(shopGoodsVo, shopGoodsImage);


            if (shopGoodsVo.getGoodsId() == null) {
                //新增
                if (shopGoods.getGoodsPrice() == null) {
                    shopGoods.setGoodsPrice(BigDecimal.ZERO);
                }
                if (shopGoods.getGoodsOriginalPrice() == null) {
                    shopGoods.setGoodsOriginalPrice(BigDecimal.ZERO);
                }
                if (shopGoods.getGoodsPoint() == null) {
                    shopGoods.setGoodsPoint(0);
                }
                if (shopGoods.getStockNum() == null) {
                    shopGoods.setStockNum(0);
                }
                if (shopGoods.getStockLockedCount() == null) {
                    shopGoods.setStockLockedCount(0);
                }
                if (shopGoods.getGoodsNo() == null) {
                    shopGoods.setGoodsNo(new SimpleDateFormat("MMddHHmmss").format(new Date()));
                }
                if (shopGoods.getEvaluateStar() == null) {
                    shopGoods.setEvaluateStar(5);
                }
                if (shopGoods.getSaleType() == null) {
                    shopGoods.setSaleType("0");
                }
                if (shopGoods.getSalePlatform() == null) {
                    shopGoods.setSalePlatform("0");
                }
                if (shopGoods.getCommendType() == null) {
                    shopGoods.setCommendType("0");
                }
                if (shopGoods.getStatus() == null) {
                    shopGoods.setStatus("0");
                }
                shopGoods.setExchangeNum(0);
                Long id = shopGoodsMapper.insertReturnId(shopGoods);
                shopGoodsImage.setGoodsId(shopGoods.getGoodsId());
                shopGoodsImageService.insertSelective(shopGoodsImage);
            } else {
                //修改
                ShopGoods shopGoodsOld = shopGoodsMapper.selectByPrimaryKey(shopGoods.getGoodsId());
                //优惠券判断，
                if (shopGoodsOld.getTicketTypeId() != null) {
                    TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(shopGoodsOld.getTicketTypeId());
                    if (tenantTicketType == null) {
                        return TResponse.FAIL("所选优惠券不存在!");
                    }
                    if (tenantTicketType != null && "1".equals(tenantTicketType.getStatus()) && shopGoodsVo.getStatus() != null && "1".equals(shopGoodsVo.getStatus())) {
                        return TResponse.FAIL("所选优惠券已停止使用，请先启用优惠券!");
                    }
                }

                shopGoodsMapper.updateByPrimaryKeySelective(shopGoods);
                shopGoodsImageService.updateByPrimaryKeySelective(shopGoodsImage);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            return TResponse.FAIL();
        }
    }

    @Override
    public void addOrReduceShopGoods(ShopGoods shopGoods, int type, String remark, int num) {
        //type 0补货，1减货
        //0订单发货 1订单退货 2后台减货 3后台进货
        if (shopGoods.getStockNum() == null) {
            shopGoods.setStockNum(0);
        }
        if (type == 0) {
            shopGoods.setStockNum(shopGoods.getStockNum() + num);
        } else {
            shopGoods.setStockNum(shopGoods.getStockNum() - num);
        }
        shopGoods.setLastUpdatedTime(new Date());

        shopGoodsMapper.updateByPrimaryKeySelective(shopGoods);

        //补货减货订单录入
        ShopStockRecord shopStockRecord = new ShopStockRecord();

        if (type == 0) {
            shopStockRecord.setStockRecordType("3");
        } else {
            shopStockRecord.setStockRecordType("2");
        }
        shopStockRecord.setTenantCode(shopGoods.getTenantCode());
        shopStockRecord.setRemark(remark);
        shopStockRecord.setCreatedTime(new Date());
        shopStockRecord.setLastUpdatedTime(new Date());
        shopStockRecord.setShopGoodsId(shopGoods.getGoodsId());
        shopStockRecord.setStockNum(shopGoods.getStockNum());
        shopStockRecord.setVariation(num);
        shopStockRecordService.insertSelective(shopStockRecord);
    }

    @Override
    public TResponse deleteImages(WebUploader webUploader, ShopGoodsVo shopGoodsVo) {

        ShopGoods shopGoods = shopGoodsMapper.selectByPrimaryKey(shopGoodsVo.getGoodsId());
        ShopGoodsImage shopGoodsImage = shopGoodsImageService.selectByPrimaryKey(shopGoodsVo.getGoodsId());

        try {
            if (shopGoodsVo.getGoodsImage() != null) {
                webUploader.deleteFile(shopGoodsVo.getGoodsImage());
                shopGoods.setGoodsImage(null);
                shopGoods.setLastUpdatedTime(new Date());
                shopGoodsMapper.updateByPrimaryKey(shopGoods);
            }
            if (shopGoodsVo.getImageBroadcast1() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageBroadcast1());
                shopGoodsImage.setImageBroadcast1(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            if (shopGoodsVo.getImageBroadcast2() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageBroadcast2());
                shopGoodsImage.setImageBroadcast2(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            if (shopGoodsVo.getImageBroadcast3() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageBroadcast3());
                shopGoodsImage.setImageBroadcast3(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            if (shopGoodsVo.getImageBroadcast4() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageBroadcast4());
                shopGoodsImage.setImageBroadcast4(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            if (shopGoodsVo.getImageBroadcast5() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageBroadcast5());
                shopGoodsImage.setImageBroadcast5(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            if (shopGoodsVo.getImageDetail1() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageDetail1());
                shopGoodsImage.setImageDetail1(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            if (shopGoodsVo.getImageDetail2() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageDetail2());
                shopGoodsImage.setImageDetail2(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            if (shopGoodsVo.getImageDetail3() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageDetail3());
                shopGoodsImage.setImageDetail3(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            if (shopGoodsVo.getImageOriginal() != null) {
                webUploader.deleteFile(shopGoodsVo.getImageOriginal());
                shopGoodsImage.setImageOriginal(null);
                shopGoodsImage.setLastUpdatedTime(new Date());
                shopGoodsImageService.updateByPrimaryKey(shopGoodsImage);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
            return TResponse.FAIL();
        }

    }

    @Override
    public List<ShopGoods> listByTicketTypeId(Long ticketTypeId) {
        ShopGoodsExample example = new ShopGoodsExample();
        example.createCriteria().andTicketTypeIdEqualTo(ticketTypeId).andStatusEqualTo("1");
        return shopGoodsMapper.selectByExample(example);
    }

    @Override
    public TResponse updateShopGoods(Long shopOrderId, TenantUser user) {
        ShopOrder shopOrder = shopOrderMapper.selectByPrimaryKey(shopOrderId);

        //退货申请记录（有效关联）
        ShopOrderReturnApply shopOrderReturnApply=shopOrderReturnApplyMapper.selectShopOrderReturnApplyByShopOrderId(shopOrderId);

        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(shopOrder.getMemberId());

        ShopOrderGoodsExample example = new ShopOrderGoodsExample();
        example.createCriteria().andShopOrderIdEqualTo(shopOrderId);
        ShopOrderGoods shopOrderGoods = shopOrderGoodsService.selectByExample(example).get(0);

        ShopGoods shopGoods = this.selectByPrimaryKey(shopOrderGoods.getGoodsId());

        //下单数量
        Integer goodsNum = shopOrderGoods.getGoodsNum();
        Integer stockNum=shopGoods.getStockNum();
        shopGoods.setStockNum(stockNum + goodsNum);
        shopGoods.setExchangeNum(shopGoods.getExchangeNum() - goodsNum);
        shopGoods.setLastUpdatedBy(user.getLoginName());
        shopGoods.setLastUpdatedTime(new Date());
        //修改商品库存数量
        this.updateByPrimaryKeySelective(shopGoods);
        ////下单数量
        //Integer goodsNum = shopOrderGoods.getGoodsNum();
        //Integer stockNum = shopGoods.getStockNum();
        ////待发货订单
        //if ("0".equals(shopOrderReturnApply.getGoodsStatus())) {
        //    shopGoods.setStockNum(stockNum);
        //    shopGoods.setStockLockedCount(shopGoods.getStockLockedCount() - goodsNum);
        //    shopGoods.setExchangeNum(shopGoods.getExchangeNum());
        //} else if ("1".equals(shopOrderReturnApply.getGoodsStatus())) {
        //    //已发货订单
        //    shopGoods.setStockNum(stockNum + goodsNum);
        //    shopGoods.setExchangeNum(shopGoods.getExchangeNum() - goodsNum);
        //}
        //shopGoods.setLastUpdatedBy(user.getLoginName());
        //shopGoods.setLastUpdatedTime(new Date());
        //
        ////修改退货申请状态
        //shopOrderReturnApply.setStatus("2");
        //shopOrderReturnApplyMapper.updateByPrimaryKey(shopOrderReturnApply);
        //
        ////修改商品库存数量
        //this.updateByPrimaryKeySelective(shopGoods);

        //新增库存变动记录（订单退货）
        ShopStockRecord shopStockRecord = new ShopStockRecord();
        shopStockRecord.setTenantCode(user.getTenantCode());
        shopStockRecord.setShopGoodsId(shopGoods.getGoodsId());
        shopStockRecord.setStockRecordType("1");
        shopStockRecord.setShopOrderId(shopOrderId);
        shopStockRecord.setVariation(goodsNum);
        shopStockRecord.setStockNum(shopGoods.getStockNum());
        shopStockRecord.setRemark("订单退货");
        shopStockRecord.setCreatedBy(user.getLoginName());
        shopStockRecord.setCreatedTime(new Date());
        shopStockRecordMapper.insertSelective(shopStockRecord);

        //修改会员账户member_account
        MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(shopOrder.getMemberId());
        memberAccount.setPoint(memberAccount.getPoint() + shopOrder.getUsePoint());
        memberAccount.setLastUpdatedBy(user.getLoginName());
        memberAccount.setLastUpdatedTime(new Date());
        memberAccountMapper.updateByPrimaryKeySelective(memberAccount);

        //退货退回积分
        UgsMemberPointRecord ugsMemberPointRecord = new UgsMemberPointRecord();
        ugsMemberPointRecord.setTenantCode(shopOrder.getTenantCode());
        ugsMemberPointRecord.setMemberId(shopOrder.getMemberId());
        ugsMemberPointRecord.setMemberType(memberInfo.getMemberType());
        ugsMemberPointRecord.setRecordType("6");
        ugsMemberPointRecord.setShopOrderId(shopOrderId);
        ugsMemberPointRecord.setShopOrderNum(shopOrder.getShopOrderNum());
        ugsMemberPointRecord.setPoint(shopOrder.getUsePoint());

        UgsMemberPointRecordExample ugsMemberPointRecordExample = new UgsMemberPointRecordExample();
        ugsMemberPointRecordExample.createCriteria().andMemberIdEqualTo(shopOrder.getMemberId());
        ugsMemberPointRecordExample.setOrderByClause("created_time desc");
        List<UgsMemberPointRecord> ugsMemberPointRecords = ugsMemberPointRecordMapper.selectByExample(ugsMemberPointRecordExample);
        if (!CollectionUtils.isEmpty(ugsMemberPointRecords)) {
            ugsMemberPointRecord.setResult(ugsMemberPointRecords.get(0).getResult() + shopOrder.getUsePoint());
            ugsMemberPointRecord.setPointTypeId(ugsMemberPointRecords.get(0).getPointTypeId());
        }
        ugsMemberPointRecord.setRemark("商品退货退回积分");
        ugsMemberPointRecord.setCreatedBy(user.getLoginName());
        ugsMemberPointRecord.setCreatedTime(new Date());
        ugsMemberPointRecordMapper.insertSelective(ugsMemberPointRecord);

        //如果商品是优惠券类型
        //if ("0".equals(shopGoods.getSalePlatform())) {
        //    TenantTicketType tenantTicketType = tenantTicketTypeService.selectByPrimaryKey(shopGoods.getTicketTypeId());
        //    //修改tenant_ticket_type记录
        //    tenantTicketType.setTotalTicket(tenantTicketType.getTotalTicket() - shopOrderGoods.getGoodsNum());
        //    tenantTicketType.setRemainTicket(tenantTicketType.getRemainTicket() + shopOrderGoods.getGoodsNum());
        //    tenantTicketTypeService.updateByPrimaryKeySelective(tenantTicketType);
        //
        //    //删除用户优惠券余额记录
        //    MemberTicketExample memberTicketExample = new MemberTicketExample();
        //    memberTicketExample.createCriteria()
        //            .andTenantCodeEqualTo(shopOrder.getTenantCode())
        //            .andMemberIdEqualTo(shopOrder.getMemberId())
        //            .andTicketTypeIdEqualTo(shopGoods.getTicketTypeId())
        //            .andTicketSourceEqualTo("4");
        //    List<MemberTicket> memberTickets = memberTicketMapper.selectByExample(memberTicketExample);
        //    if (!CollectionUtils.isEmpty(memberTickets)) {
        //        List<Long> tenantTicketSendRecordIds = memberTickets.stream().map(memberTicket -> memberTicket.getTicketSendRecordId()).distinct().collect(Collectors.toList());
        //        //删除优惠券发放记录
        //        TenantTicketSendRecordExample tenantTicketSendRecordExample = new TenantTicketSendRecordExample();
        //        tenantTicketSendRecordExample.createCriteria().andTicketSendRecordIdIn(tenantTicketSendRecordIds);
        //        tenantTicketSendRecordMapper.deleteByExample(tenantTicketSendRecordExample);
        //    }
        //    memberTicketMapper.deleteByExample(memberTicketExample);
        //
        //}
        return TResponse.SUCCESS();

    }
}
